package cn.com.easy.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import cn.com.easy.exception.BusinessException;

/**
 * jdk原生序列化工具类
 * 
 * @author nibili 2017年11月30日
 * 
 */
public class JdkSerializerUtils {

	/**
	 * 序列化
	 * 
	 * @param obj
	 * @return
	 * @author nibili 2017年11月30日
	 * @throws BusinessException
	 */
	public static byte[] serialize(Object obj) throws BusinessException {
		if (obj == null) {
			return new byte[0];
		}
		byte[] bytes = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			ObjectOutputStream oos = new ObjectOutputStream(bos);
			oos.writeObject(obj);
			oos.flush();
			bytes = bos.toByteArray();
			oos.close();
			bos.close();
		} catch (Exception ex) {
			throw new BusinessException("序列化对象异常", ex);
		}
		return bytes;
	}

	/**
	 * 反序列化
	 * 
	 * @param bytes
	 * @return
	 * @throws SerializationException
	 * @author nibili 2017年11月30日
	 */
	public static Object deserialize(byte[] bytes) throws BusinessException {
		if (bytes == null || bytes.length <= 0) {
			return null;
		}
		Object obj = null;
		try {
			ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
			ObjectInputStream ois = new ObjectInputStream(bis);
			obj = ois.readObject();
			ois.close();
			bis.close();
		} catch (Exception ex) {
			throw new BusinessException("反序列化对象异常", ex);
		}
		return obj;
	}

}
